package org.anupta.realm.server.inter;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;

import org.anupta.realm.server.inter.client.InterClient;
import org.anupta.realm.utils.others.Config;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class InterServer {
	private IoAcceptor acceptor = new NioSocketAcceptor();
	
	public InterServer(){
        acceptor.setHandler(new InterHandler());
	}
	
	public void bind(int port){
		try {
			acceptor.bind(new InetSocketAddress(Config.INTER_IP,port));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public ArrayList<InterClient> getAllClient(){
		ArrayList<InterClient> client = new ArrayList<InterClient>();
		for(IoSession session : acceptor.getManagedSessions().values()){
			if(session.getAttribute("client") instanceof InterClient){
				client.add((InterClient)session.getAttribute("client"));
			}
		}
		return client;
	}
	
	public InterClient getClient(int guid){
		for(IoSession session : acceptor.getManagedSessions().values()){
			if(session.getAttribute("client") instanceof InterClient){
				InterClient client = (InterClient)session.getAttribute("client");
				if(client.getGuid() == guid){
					return client;
				}
			}
		}
		return null;
	}
	
	public void close(){
		acceptor.unbind();
		acceptor.dispose(true);
	}
}
